package se.kth.seds.mi.ui;

import se.kth.seds.mi.communication.Server;
import se.kth.seds.mi.core.common.HashAlgorithm;
import se.kth.seds.mi.core.crypto.keypair.KeyPairCrypto;
import se.kth.seds.mi.core.exceptions.OperationFailedException;

import java.io.IOException;
import java.security.PublicKey;

import org.apache.catalina.util.HexUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.swing.*;

/**
 * Created by IntelliJ IDEA.
 * User: Sike Huang
 * Date: Nov 21, 2008
 * Time: 8:04:03 PM
 * To change this template use File | Settings | File Templates.
 */
public class KeyPairReceiverFrame extends javax.swing.JFrame {
    private Log logger = LogFactory.getLog(getClass());

    private Server server;
    private KeyPairCrypto keyPairCrypto;
    private PublicKey receivedPublicKey;
    private String receivedSignature;
    private String receviedMessage;

    public void setServer(Server server) {
        this.server = server;
    }

    public void setKeyPairCrypto(KeyPairCrypto keyPairCrypto) {
        this.keyPairCrypto = keyPairCrypto;
    }

    /**
     * This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jLabel_heading = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea_receivedMessage = new javax.swing.JTextArea();
        jLabel_receivedMessage = new javax.swing.JLabel();
        jComboBox_hashSignFunc = new javax.swing.JComboBox();
        jLabel_hashSignFunc = new javax.swing.JLabel();
        jScrollPane3 = new javax.swing.JScrollPane();
        jTextArea_receivedSignature = new javax.swing.JTextArea();
        jLabel_receivedSignature = new javax.swing.JLabel();
        jLabel_hint_mac_encrpted = new javax.swing.JLabel();
        jScrollPane4 = new javax.swing.JScrollPane();
        jTextArea_receivedPublicKey = new javax.swing.JTextArea();
        jLabel_receivedPublicKey = new javax.swing.JLabel();
        jButton_verify = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setName("Form"); // NOI18N

        jLabel_heading.setText("Key Pair Receiver"); // NOI18N
        jLabel_heading.setName("jLabel_heading"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        jTextArea_receivedMessage.setColumns(20);
        jTextArea_receivedMessage.setEditable(false);
        jTextArea_receivedMessage.setLineWrap(true);
        jTextArea_receivedMessage.setRows(5);
        jTextArea_receivedMessage.setName("jTextArea_receivedMessage"); // NOI18N
        jScrollPane1.setViewportView(jTextArea_receivedMessage);

        jLabel_receivedMessage.setText("Received Message:"); // NOI18N
        jLabel_receivedMessage.setName("jLabel_receivedMessage"); // NOI18N

        jComboBox_hashSignFunc.setModel(new javax.swing.DefaultComboBoxModel(new String[]{"Item 1", "Item 2", "Item 3", "Item 4"}));
        jComboBox_hashSignFunc.setName("jComboBox_hashSignFunc"); // NOI18N

        jLabel_hashSignFunc.setText("Hash & Sign Func:"); // NOI18N
        jLabel_hashSignFunc.setName("jLabel_hashSignFunc"); // NOI18N

        jScrollPane3.setName("jScrollPane3"); // NOI18N

        jTextArea_receivedSignature.setColumns(20);
        jTextArea_receivedSignature.setEditable(false);
        jTextArea_receivedSignature.setLineWrap(true);
        jTextArea_receivedSignature.setRows(5);
        jTextArea_receivedSignature.setName("jTextArea_receivedSignature"); // NOI18N
        jScrollPane3.setViewportView(jTextArea_receivedSignature);

        jLabel_receivedSignature.setText("Received Signature:"); // NOI18N
        jLabel_receivedSignature.setName("jLabel_receivedSignature"); // NOI18N

        jLabel_hint_mac_encrpted.setText("(MAC Encrpted by Private Key)"); // NOI18N
        jLabel_hint_mac_encrpted.setName("jLabel_hint_mac_encrpted"); // NOI18N

        jScrollPane4.setName("jScrollPane4"); // NOI18N

        jTextArea_receivedPublicKey.setColumns(20);
        jTextArea_receivedPublicKey.setEditable(false);
        jTextArea_receivedPublicKey.setLineWrap(true);
        jTextArea_receivedPublicKey.setRows(5);
        jTextArea_receivedPublicKey.setName("jTextArea_receivedPublicKey"); // NOI18N
        jScrollPane4.setViewportView(jTextArea_receivedPublicKey);

        jLabel_receivedPublicKey.setText("Received Public Key:"); // NOI18N
        jLabel_receivedPublicKey.setName("jLabel_receivedPublicKey"); // NOI18N

        jButton_verify.setText("Verify"); // NOI18N
        jButton_verify.setName("jButton_verify"); // NOI18N
        jButton_verify.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_verifyActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                                .addGap(165, 165, 165)
                                .addComponent(jLabel_heading)
                                .addContainerGap(177, Short.MAX_VALUE))
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                        .addGroup(layout.createSequentialGroup()
                                                                .addContainerGap(13, Short.MAX_VALUE)
                                                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                                        .addComponent(jLabel_receivedMessage)
                                                                        .addComponent(jLabel_hashSignFunc))
                                                                .addGap(109, 109, 109))
                                                        .addGroup(layout.createSequentialGroup()
                                                        .addContainerGap()
                                                        .addComponent(jLabel_receivedSignature)
                                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
                                                .addGroup(layout.createSequentialGroup()
                                                .addContainerGap()
                                                .addComponent(jLabel_hint_mac_encrpted)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
                                        .addGroup(layout.createSequentialGroup()
                                        .addContainerGap()
                                        .addComponent(jLabel_receivedPublicKey)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                        .addComponent(jComboBox_hashSignFunc, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING)))
                                .addGap(45, 45, 45))
                        .addGroup(layout.createSequentialGroup()
                        .addGap(135, 135, 135)
                        .addComponent(jButton_verify, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap(182, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel_heading)
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jLabel_receivedMessage)
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jComboBox_hashSignFunc, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jLabel_hashSignFunc))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel_receivedSignature)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel_hint_mac_encrpted)))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jLabel_receivedPublicKey))
                        .addGap(18, 18, 18)
                        .addComponent(jButton_verify)
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );


        try {
            server.read(this);
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

        jComboBox_hashSignFunc.setModel(new DefaultComboBoxModel(HashAlgorithm.values()));
        setVisible(true);
        pack();
    }// </editor-fold>

    private void jButton_verifyActionPerformed(java.awt.event.ActionEvent evt) {
        if (receviedMessage == null || receivedSignature == null) {
            JOptionPane.showMessageDialog(this, "No message has been received!", "Validation Error", JOptionPane.ERROR_MESSAGE);
            return;
        }
        if (receivedPublicKey == null) {
            JOptionPane.showMessageDialog(this, "No public key has been received!", "Validation Error", JOptionPane.ERROR_MESSAGE);
            return;
        }
        keyPairCrypto.setHashAlgorithm((HashAlgorithm) jComboBox_hashSignFunc.getSelectedItem());
        keyPairCrypto.setMessage(receviedMessage);
        try {
            boolean isValid = keyPairCrypto.verify(receivedPublicKey, receivedSignature);
            if (isValid) {
                JOptionPane.showMessageDialog(this, "Message integrity is valid", "Verification", JOptionPane.INFORMATION_MESSAGE);
            } else {
                JOptionPane.showMessageDialog(this, "Message integrity is invalid! (hint: please check your hash & encode func)", "Verification", JOptionPane.ERROR_MESSAGE);
            }
        } catch (OperationFailedException e) {
            logger.error(e);
            JOptionPane.showMessageDialog(this, "Message integrity is invalid! (hint: please check your hash & encode func)", "Verification", JOptionPane.ERROR_MESSAGE);
        }
    }

    public void setMessage(String receivedMessage) {
        this.receviedMessage = receivedMessage;
        jTextArea_receivedMessage.setText(receivedMessage);
    }

    public void setSignature(String receivedSignature) {
        this.receivedSignature = receivedSignature;
        jTextArea_receivedSignature.setText(receivedSignature);
    }

    public void setReceivedPublicKey(PublicKey receivedPublicKey) {
        this.receivedPublicKey = receivedPublicKey;
        jTextArea_receivedPublicKey.setText(HexUtils.convert(receivedPublicKey.getEncoded()));
    }

    // Variables declaration - do not modify
    private javax.swing.JButton jButton_verify;
    private javax.swing.JComboBox jComboBox_hashSignFunc;
    private javax.swing.JLabel jLabel_hashSignFunc;
    private javax.swing.JLabel jLabel_heading;
    private javax.swing.JLabel jLabel_hint_mac_encrpted;
    private javax.swing.JLabel jLabel_receivedMessage;
    private javax.swing.JLabel jLabel_receivedPublicKey;
    private javax.swing.JLabel jLabel_receivedSignature;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JTextArea jTextArea_receivedMessage;
    private javax.swing.JTextArea jTextArea_receivedPublicKey;
    private javax.swing.JTextArea jTextArea_receivedSignature;
    // End of variables declaration

}
